﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using DAC.Simulator.Services;

namespace DAC.Simulator
{
    public partial class SimulatorForm : Form
    {
        private ServiceHost _dacUserServiceHost = null;
        public static ILogInterface UserServiceLogger { get; private set; }

        public SimulatorForm()
        {
            InitializeComponent();
            UserServiceLogger = new SimulatorLogger(this.rtbOutput, "User Service", Color.DarkGray);

            StartService();
          
        }

        public void StartService()
        {
            chkUserService.Checked = true;
        }

        public void StopService()
        {
            chkUserService.Checked = false;
        }

        private void SimulatorForm_Load(object sender, EventArgs e)
        {

        }

        private void SimulatorForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_dacUserServiceHost != null && (_dacUserServiceHost.State == CommunicationState.Opened))
            {
                _dacUserServiceHost.Close();
                _dacUserServiceHost = null;
            }
        }

        private void chkUserService_CheckedChanged(object sender, EventArgs e)
        {
            if (chkUserService.Checked)
            {
                if (_dacUserServiceHost == null)
                {
                    var dacUserService = new DACUserServiceAdapter();
                   
                    _dacUserServiceHost = new ServiceHost(dacUserService);
                    //_dacUserServiceHost.SetEndpointAddress()
                    _dacUserServiceHost.Open();

                    UserServiceLogger.WriteLine(string.Format("DAC User Service simulator listening at {0}", _dacUserServiceHost.Description.Endpoints[0].Address.Uri.ToString()));

                }
            }
            else
            {
                if (_dacUserServiceHost != null && (_dacUserServiceHost.State == CommunicationState.Opened))
                {
                    _dacUserServiceHost.Close();
                    _dacUserServiceHost = null;
                    UserServiceLogger.WriteLine("DAC User Service simulator stopped listening");

                }
            }
        }
    }
}
